#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

反沙箱和反分析技术模块
集成多种对抗分析环境和逆向工程的技术
"""

import os
import sys
import time
import psutil
import socket
import hashlib
import subprocess
import threading
import random
import string
from typing import List, Dict, Optional, Tuple, Any
import platform
import ctypes
import struct

class SandboxDetector:
    """沙箱环境检测器"""
    
    def __init__(self):
        self.name = "沙箱环境检测器"
        
        # 已知沙箱特征
        self.sandbox_indicators = {
            'processes': [
                'vboxservice', 'vboxtray', 'vmtoolsd', 'vmwaretray',
                'vmwareuser', 'vmsrvc', 'vmusrvc', 'prl_cc', 'prl_tools',
                'xenservice', 'qemu-ga', 'windanr', 'sample', 'malware',
                'sandbox', 'virus', 'analyst'
            ],
            'files': [
                '/usr/bin/vboxmanage', '/usr/bin/VBoxService',
                '/usr/bin/vmware-toolbox-cmd', '/usr/bin/vmtoolsd',
                '/proc/vz', '/proc/bc', '/proc/xen',
                '/sys/bus/acpi/devices/VBOX0000',
                '/sys/bus/acpi/devices/VMW0001'
            ],

            'mac_addresses': [
                '00:0C:29', '00:1C:14', '00:50:56',  # VMware
                '08:00:27',  # VirtualBox
                '00:16:3E',  # Xen
                '00:1C:42'   # Parallels
            ],
            'hostnames': [
                'sandbox', 'malware', 'virus', 'sample',
                'analysis', 'cuckoo', 'vmware', 'vbox'
            ]
        }
    
    def detect_virtualization(self) -> Dict[str, Any]:
        """检测虚拟化环境"""
        results = {
            'is_virtualized': False,
            'vm_type': None,
            'confidence': 0,
            'indicators': []
        }
        
        # 检测方法1: 进程检测
        vm_processes = self._check_vm_processes()
        if vm_processes:
            results['indicators'].extend(vm_processes)
            results['confidence'] += 30
        
        # 检测方法2: 文件系统检测
        vm_files = self._check_vm_files()
        if vm_files:
            results['indicators'].extend(vm_files)
            results['confidence'] += 25
        
        # 检测方法3: 硬件特征检测
        hw_indicators = self._check_hardware_indicators()
        if hw_indicators:
            results['indicators'].extend(hw_indicators)
            results['confidence'] += 20
        
        # 检测方法4: 网络接口检测
        net_indicators = self._check_network_indicators()
        if net_indicators:
            results['indicators'].extend(net_indicators)
            results['confidence'] += 15
        
        # 检测方法5: 系统信息检测
        sys_indicators = self._check_system_indicators()
        if sys_indicators:
            results['indicators'].extend(sys_indicators)
            results['confidence'] += 10
        
        # 判断虚拟化类型
        if results['confidence'] > 50:
            results['is_virtualized'] = True
            results['vm_type'] = self._determine_vm_type(results['indicators'])
        
        return results
    
    def _check_vm_processes(self) -> List[str]:
        """检查虚拟机相关进程"""
        found_processes = []
        try:
            for proc in psutil.process_iter(['name']):
                proc_name = proc.info['name'].lower()
                for indicator in self.sandbox_indicators['processes']:
                    if indicator in proc_name:
                        found_processes.append("Process: {}".format(proc_name))
        except:
            pass
        return found_processes
    
    def _check_vm_files(self) -> List[str]:
        """检查虚拟机相关文件"""
        found_files = []
        for file_path in self.sandbox_indicators['files']:
            if os.path.exists(file_path):
                found_files.append("File: {}".format(file_path))
        return found_files
    
    def _check_hardware_indicators(self) -> List[str]:
        """检查硬件指标"""
        indicators = []
        
        try:
            # CPU核心数检测
            cpu_count = psutil.cpu_count()
            if cpu_count <= 2:
                indicators.append("Low CPU count: {}".format(cpu_count))
            
            # 内存大小检测
            memory = psutil.virtual_memory().total / (1024**3)  # GB
            if memory <= 2:
                indicators.append("Low memory: {:.1f}GB".format(memory))
            
            # 磁盘大小检测
            disk = psutil.disk_usage('/').total / (1024**3)  # GB
            if disk <= 50:
                indicators.append("Small disk: {:.1f}GB".format(disk))
            
        except:
            pass
        
        return indicators
    
    def _check_network_indicators(self) -> List[str]:
        """检查网络指标"""
        indicators = []
        
        try:
            # MAC地址检测
            for interface, addrs in psutil.net_if_addrs().items():
                for addr in addrs:
                    if addr.family == psutil.AF_LINK:
                        mac = addr.address.upper()
                        for vm_mac in self.sandbox_indicators['mac_addresses']:
                            if mac.startswith(vm_mac.upper()):
                                indicators.append("VM MAC: {}".format(mac))
        except:
            pass
        
        return indicators
    
    def _check_system_indicators(self) -> List[str]:
        """检查系统指标"""
        indicators = []
        
        try:
            # 主机名检测
            hostname = socket.gethostname().lower()
            for indicator in self.sandbox_indicators['hostnames']:
                if indicator in hostname:
                    indicators.append("Suspicious hostname: {}".format(hostname))
            
            # 系统信息检测
            system_info = platform.platform().lower()
            if 'vmware' in system_info or 'virtualbox' in system_info:
                indicators.append("VM in platform: {}".format(system_info))
            
        except:
            pass
        
        return indicators
    
    def _determine_vm_type(self, indicators: List[str]) -> str:
        """确定虚拟机类型"""
        indicator_text = ' '.join(indicators).lower()
        
        if 'vmware' in indicator_text:
            return 'VMware'
        elif 'vbox' in indicator_text or 'virtualbox' in indicator_text:
            return 'VirtualBox'
        elif 'xen' in indicator_text:
            return 'Xen'
        elif 'qemu' in indicator_text:
            return 'QEMU'
        elif 'parallels' in indicator_text:
            return 'Parallels'
        else:
            return 'Unknown'

class DebuggerDetector:
    """调试器检测器"""
    
    def __init__(self):
        self.name = "调试器检测器"
        
        self.debugger_processes = [
            'gdb', 'strace', 'ltrace', 'objdump', 'readelf',
            'hexdump', 'xxd', 'strings', 'nm', 'ldd',
            'valgrind', 'perf', 'ftrace'
        ]
    
    def detect_debugger(self) -> Dict[str, Any]:
        """检测调试器"""
        results = {
            'debugger_detected': False,
            'debugger_type': None,
            'detection_methods': []
        }
        
        # 方法1: 进程检测
        if self._check_debugger_processes():
            results['debugger_detected'] = True
            results['detection_methods'].append('process_detection')
        
        # 方法2: ptrace检测
        if self._check_ptrace():
            results['debugger_detected'] = True
            results['detection_methods'].append('ptrace_detection')
        
        # 方法3: 父进程检测
        if self._check_parent_process():
            results['debugger_detected'] = True
            results['detection_methods'].append('parent_process_detection')
        
        # 方法4: 时间检测
        if self._check_timing_attack():
            results['debugger_detected'] = True
            results['detection_methods'].append('timing_detection')
        
        return results
    
    def _check_debugger_processes(self) -> bool:
        """检查调试器进程"""
        try:
            for proc in psutil.process_iter(['name']):
                proc_name = proc.info['name'].lower()
                if proc_name in self.debugger_processes:
                    return True
        except:
            pass
        return False
    
    def _check_ptrace(self) -> bool:
        """检查ptrace状态"""
        try:
            # 检查/proc/self/status中的TracerPid
            with open('/proc/self/status', 'r') as f:
                for line in f:
                    if line.startswith('TracerPid:'):
                        tracer_pid = int(line.split()[1])
                        if tracer_pid != 0:
                            return True
        except:
            pass
        return False
    
    def _check_parent_process(self) -> bool:
        """检查父进程"""
        try:
            parent = psutil.Process().parent()
            if parent:
                parent_name = parent.name().lower()
                if parent_name in self.debugger_processes:
                    return True
        except:
            pass
        return False
    
    def _check_timing_attack(self) -> bool:
        """时间检测攻击"""
        try:
            # 测量简单操作的时间
            start_time = time.time()
            
            # 执行一些简单操作
            for i in range(1000):
                x = i * 2
            
            end_time = time.time()
            execution_time = end_time - start_time
            
            # 如果执行时间异常长，可能被调试
            if execution_time > 0.1:  # 100ms阈值
                return True
                
        except:
            pass
        return False

class AntiAnalysisEvasion:
    """反分析规避技术"""
    
    def __init__(self):
        self.name = "反分析规避技术"
    
    def code_obfuscation(self, code: str) -> str:
        """代码混淆"""
        try:
            # 简单的字符串混淆
            obfuscated = ""
            for char in code:
                if char.isalpha():
                    # 随机大小写
                    if random.choice([True, False]):
                        obfuscated += char.upper()
                    else:
                        obfuscated += char.lower()
                else:
                    obfuscated += char
            
            return obfuscated
        except:
            return code
    
    def string_encryption(self, text: str, key: str = None) -> Tuple[str, str]:
        """字符串加密"""
        if not key:
            key = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
        
        try:
            # 简单XOR加密
            encrypted = ""
            for i, char in enumerate(text):
                key_char = key[i % len(key)]
                encrypted_char = chr(ord(char) ^ ord(key_char))
                encrypted += encrypted_char
            
            # Base64编码
            import base64
            encoded = base64.b64encode(encrypted.encode()).decode()
            
            return encoded, key
        except:
            return text, key
    
    def anti_disassembly(self) -> bool:
        """反汇编对抗"""
        try:
            # 插入垃圾指令
            junk_operations = [
                lambda: sum(range(100)),
                lambda: [i**2 for i in range(50)],
                lambda: ''.join(random.choices(string.ascii_letters, k=100)),
                lambda: time.sleep(0.001)
            ]
            
            # 随机执行垃圾操作
            for _ in range(random.randint(1, 5)):
                operation = random.choice(junk_operations)
                operation()
            
            return True
        except:
            return False
    
    def control_flow_obfuscation(self, func_list: List[callable]) -> bool:
        """控制流混淆"""
        try:
            # 随机执行函数顺序
            shuffled_funcs = func_list.copy()
            random.shuffle(shuffled_funcs)
            
            for func in shuffled_funcs:
                if callable(func):
                    try:
                        func()
                    except:
                        pass
            
            return True
        except:
            return False

class EnvironmentFingerprinting:
    """环境指纹识别"""
    
    def __init__(self):
        self.name = "环境指纹识别"
    
    def collect_environment_info(self) -> Dict[str, Any]:
        """收集环境信息"""
        env_info = {
            'system': {},
            'hardware': {},
            'network': {},
            'processes': {},
            'users': {}
        }
        
        try:
            # 系统信息
            env_info['system'] = {
                'platform': platform.platform(),
                'architecture': platform.architecture(),
                'processor': platform.processor(),
                'python_version': platform.python_version(),
                'hostname': socket.gethostname(),
                'uptime': self._get_uptime()
            }
            
            # 硬件信息
            env_info['hardware'] = {
                'cpu_count': psutil.cpu_count(),
                'memory_total': psutil.virtual_memory().total,
                'disk_usage': psutil.disk_usage('/').total,
                'boot_time': psutil.boot_time()
            }
            
            # 网络信息
            env_info['network'] = {
                'interfaces': list(psutil.net_if_addrs().keys()),
                'connections': len(psutil.net_connections()),
                'io_stats': psutil.net_io_counters()._asdict()
            }
            
            # 进程信息
            processes = []
            for proc in psutil.process_iter(['pid', 'name', 'username']):
                processes.append(proc.info)
            env_info['processes'] = {
                'count': len(processes),
                'list': processes[:10]  # 只保存前10个
            }
            
            # 用户信息
            env_info['users'] = {
                'current_user': os.getenv('USER', 'unknown'),
                'logged_users': [user.name for user in psutil.users()]
            }
            
        except Exception as e:
            env_info['error'] = str(e)
        
        return env_info
    
    def _get_uptime(self) -> float:
        """获取系统运行时间"""
        try:
            return time.time() - psutil.boot_time()
        except:
            return 0
    
    def is_analysis_environment(self, env_info: Dict[str, Any]) -> bool:
        """判断是否为分析环境"""
        suspicious_indicators = 0
        
        try:
            # 检查系统运行时间（分析环境通常运行时间短）
            uptime_hours = env_info['system'].get('uptime', 0) / 3600
            if uptime_hours < 1:  # 运行时间少于1小时
                suspicious_indicators += 1
            
            # 检查进程数量（分析环境通常进程较少）
            process_count = env_info['processes'].get('count', 0)
            if process_count < 50:
                suspicious_indicators += 1
            
            # 检查用户数量
            logged_users = env_info['users'].get('logged_users', [])
            if len(logged_users) <= 1:
                suspicious_indicators += 1
            
            # 检查网络连接
            connections = env_info['network'].get('connections', 0)
            if connections < 10:
                suspicious_indicators += 1
            
            # 如果有3个或以上可疑指标，认为是分析环境
            return suspicious_indicators >= 3
            
        except:
            return False

class AntiAnalysisManager:
    """反分析管理器"""
    
    def __init__(self):
        self.sandbox_detector = SandboxDetector()
        self.debugger_detector = DebuggerDetector()
        self.anti_evasion = AntiAnalysisEvasion()
        self.env_fingerprinting = EnvironmentFingerprinting()
        
        self.evasion_enabled = True
        self.detection_results = {}
    
    def comprehensive_analysis_check(self) -> Dict[str, Any]:
        """全面分析环境检查"""
        results = {
            'safe_to_execute': True,
            'risk_level': 'low',
            'detections': {},
            'recommendations': []
        }
        
        # 1. 沙箱检测
        sandbox_result = self.sandbox_detector.detect_virtualization()
        results['detections']['sandbox'] = sandbox_result
        
        if sandbox_result['is_virtualized'] and sandbox_result['confidence'] > 70:
            results['safe_to_execute'] = False
            results['risk_level'] = 'high'
            results['recommendations'].append('Detected high-confidence virtualization')
        
        # 2. 调试器检测
        debugger_result = self.debugger_detector.detect_debugger()
        results['detections']['debugger'] = debugger_result
        
        if debugger_result['debugger_detected']:
            results['safe_to_execute'] = False
            results['risk_level'] = 'high'
            results['recommendations'].append('Debugger detected')
        
        # 3. 环境指纹识别
        env_info = self.env_fingerprinting.collect_environment_info()
        is_analysis_env = self.env_fingerprinting.is_analysis_environment(env_info)
        results['detections']['environment'] = {
            'info': env_info,
            'is_analysis_environment': is_analysis_env
        }
        
        if is_analysis_env:
            results['safe_to_execute'] = False
            results['risk_level'] = 'medium'
            results['recommendations'].append('Suspicious analysis environment detected')
        
        # 4. 综合风险评估
        if results['risk_level'] == 'low' and len(results['recommendations']) == 0:
            results['recommendations'].append('Environment appears safe for execution')
        
        self.detection_results = results
        return results
    
    def apply_evasion_techniques(self) -> bool:
        """应用规避技术"""
        if not self.evasion_enabled:
            return False
        
        try:
            # 1. 反汇编对抗
            self.anti_evasion.anti_disassembly()
            
            # 2. 控制流混淆
            dummy_functions = [
                lambda: time.sleep(0.001),
                lambda: random.randint(1, 100),
                lambda: len(os.listdir('.')),
                lambda: psutil.cpu_percent()
            ]
            self.anti_evasion.control_flow_obfuscation(dummy_functions)
            
            # 3. 延时执行
            delay = random.uniform(0.1, 0.5)
            time.sleep(delay)
            
            return True
            
        except Exception as e:
            return False
    
    def should_execute(self) -> bool:
        """判断是否应该执行"""
        if not hasattr(self, 'detection_results') or not self.detection_results:
            self.comprehensive_analysis_check()
        
        return self.detection_results.get('safe_to_execute', False)
    
    def get_evasion_report(self) -> Dict[str, Any]:
        """获取规避报告"""
        return {
            'detection_results': self.detection_results,
            'evasion_enabled': self.evasion_enabled,
            'timestamp': time.time(),
            'recommendations': self.detection_results.get('recommendations', [])
        }

# 装饰器：自动反分析检查
def anti_analysis_check(func):
    """反分析检查装饰器"""
    def wrapper(*args, **kwargs):
        manager = AntiAnalysisManager()
        
        # 执行检查
        if not manager.should_execute():
            print("检测到分析环境，停止执行")
            return None
        
        # 应用规避技术
        manager.apply_evasion_techniques()
        
        # 执行原函数
        return func(*args, **kwargs)
    
    return wrapper

# 使用示例
@anti_analysis_check
def sensitive_operation():
    """敏感操作示例"""
    print("执行敏感操作...")
    return "操作完成"

def demo_anti_analysis():
    """演示反分析功能"""
    manager = AntiAnalysisManager()
    
    # 全面检查
    results = manager.comprehensive_analysis_check()
    print("分析环境检查结果:")
    print("  安全执行: {}".format(results['safe_to_execute']))
    print("  风险级别: {}".format(results['risk_level']))
    print("  建议: {}".format(results['recommendations']))
    
    # 应用规避技术
    if manager.apply_evasion_techniques():
        print("规避技术已应用")
    
    # 执行敏感操作
    result = sensitive_operation()
    if result:
        print("操作结果: {}".format(result))

if __name__ == "__main__":
    demo_anti_analysis()